package com.hello.pet.service.system.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hello.pet.common.exception.BaseException;
import com.hello.pet.service.system.service.OssService;
import com.hello.pet.service.system.utils.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
@Slf4j
public class OssServiceImpl implements OssService {

    @Autowired
    private OssProperties ossProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getKeyid();
        String accessKeySecret = ossProperties.getKeysecret();
        String bucketName = ossProperties.getBucketname();
        String randomStr = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename();
        String dateStr = new DateTime().toString("yyyy/MM/dd");
        String objectName = dateStr + "/" + randomStr;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
            // 返回上传的文件url
            StringBuilder url = new StringBuilder();
            url.append("https://")
                    .append(bucketName)
                    .append(".")
                    .append(endpoint)
                    .append("/")
                    .append(objectName);
            return url.toString();
        } catch (Exception ex) {
            throw new BaseException("文件上传失败!",ex);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
